package com.spbdx.framework.config;

import cn.hutool.core.util.StrUtil;
import com.spbdx.common.utils.ServletUtils;
import com.spbdx.common.utils.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 服务相关配置
 * 
 * @author cms
 */
@Component
public class ServerConfig
{
    /**
     * 获取完整的请求路径，包括：域名，端口，上下文访问路径
     * 
     * @return 服务地址
     */
    public String getUrl()
    {
        HttpServletRequest request = ServletUtils.getRequest();
        return getDomain(request);
    }

    public static String getDomain(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        /**
         * nginx 代理加
         * proxy_set_header X-Forwarded-Proto $scheme;
         */
        String protocol = request.getHeader("X-Forwarded-Proto");
        if (StrUtil.isEmpty(protocol)) {
            String origin = request.getHeader("origin");
            if (StrUtil.startWith(origin, "https://")) {
                protocol = "https";
            } else if (StrUtil.startWith(origin, "http://")) {
                protocol = "http";
            }
        }
        if (StrUtil.isEmpty(protocol)) {
            String referer = request.getHeader("referer");
            if (StrUtil.startWith(referer, "https://")) {
                protocol = "https";
            } else if (StrUtil.startWith(referer, "http://")) {
                protocol = "http";
            }
        }
        String s = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
        if (StringUtils.isNotEmpty(protocol)) {
            s = StringUtils.replace(s, "http:", protocol + ":");
            s = StringUtils.replace(s, "https:", protocol + ":");
        }
        return s;
    }
}
